/*
	The MIT License

	Copyright (c) 2008 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <math.h>

#include "cutil_math.h"


#define CUDA_CHECK(call)	\
	do {					\
		if (call!=cudaSuccess) { assert(0 && #call); }			\
	} while (0);


texture<unsigned char, 3, cudaReadModeNormalizedFloat>	mri_data;
cudaArray	*mri_data_array = NULL;


typedef struct {
    float4 m[4];
} float4x4;

__constant__	float4x4	inv_view_matrix;

struct Ray {
	float3 o;	// origin
	float3 d;	// direction
};

//
//	intersectBox
//	http://www.siggraph.org/education/materials/HyperGraph/raytrace/rtinter3.htm
//
__device__
int intersectBox(Ray r, float3 boxmin, float3 boxmax, float *tnear, float *tfar)
{
    // compute intersection of ray with all six bbox planes
    float3 invR = make_float3(1.0f) / r.d;
    float3 tbot = invR * (boxmin - r.o);
    float3 ttop = invR * (boxmax - r.o);

    // re-order intersections to find smallest and largest on each axis
    float3 tmin = fminf(ttop, tbot);
    float3 tmax = fmaxf(ttop, tbot);

    // find the largest tmin and the smallest tmax
    float largest_tmin = fmaxf(fmaxf(tmin.x, tmin.y), fmaxf(tmin.x, tmin.z));
    float smallest_tmax = fminf(fminf(tmax.x, tmax.y), fminf(tmax.x, tmax.z));

	*tnear = largest_tmin;
	*tfar = smallest_tmax;

	return smallest_tmax > largest_tmin;
}


__device__
float4 XForm(const float4x4 &M, const float4 &v)
{
    float4 r;
    r.x = dot(v, M.m[0]);
    r.y = dot(v, M.m[1]);
    r.z = dot(v, M.m[2]);
    r.w = dot(v, M.m[3]);
    return r;
}



//
//	CUDA_SetupMRIData
//
extern "C" 
void CUDA_SetupMRIData(char *host_ptr, int w, int h, int d)
{
    cudaChannelFormatDesc desc = cudaCreateChannelDesc<unsigned char>();

	cudaExtent ce;
	ce.width  = w;
	ce.height = h;
	ce.depth  = d;
    CUDA_CHECK( cudaMalloc3DArray(&mri_data_array, &desc, ce) );

    cudaMemcpy3DParms copyParams = {0};
    copyParams.srcPtr   = make_cudaPitchedPtr((void*)host_ptr, w*sizeof(unsigned char), w, h);
    copyParams.dstArray = mri_data_array;
    copyParams.extent   = ce;
    copyParams.kind     = cudaMemcpyHostToDevice;
    CUDA_CHECK( cudaMemcpy3D(&copyParams) );
    
    
    mri_data.normalized = true;                      // access with normalized texture coordinates
    mri_data.filterMode = cudaFilterModeLinear;      // linear interpolation
    mri_data.addressMode[0] = cudaAddressModeWrap;   // wrap texture coordinates
    mri_data.addressMode[1] = cudaAddressModeWrap;
    mri_data.addressMode[2] = cudaAddressModeWrap;
    
    CUDA_CHECK( cudaBindTextureToArray(mri_data, mri_data_array) );
    
}


struct traceResult_t {
		float4	color;
		float3	normal;
		float4	pos;
		float	t;
	};


//
//	CUDA_Tracer
//
__global__ void CUDA_Tracer(float4 *color, int w, int h, float __t) 
{
    int x = blockIdx.x*blockDim.x + threadIdx.x;
    int y = blockIdx.y*blockDim.y + threadIdx.y;
	if (x >= w || y >= h) return;
    float4* pixel;
    pixel = (color + y*w + x);

    float u = (x / (float) w) * 2 - 1;
    float v = (y / (float) h) * 2 - 1;

	//-------------------------------------------
	//	Trace ray to the cube :    
    Ray r;
	float4 ray_dir  = XForm( inv_view_matrix, make_float4(u, v, -1.0f, 0) );
    float4 ray_orig = XForm( inv_view_matrix, make_float4(0, 0,  0.0f, 1) );
    r.o = make_float3( ray_orig.x, ray_orig.y, ray_orig.z ) / ray_orig.w;
    r.d = make_float3( ray_dir.x,  ray_dir.y,  ray_dir.z );

	float  s = 1.0;
	float ss = 140.0f/256.0f;
    float3 box_min = make_float3(-s, -s, -ss);
    float3 box_max = make_float3( s,  s,  ss);

	float dnear = 0, dfar = 1;
    
	int hit = intersectBox(r, box_min, box_max, &dnear, &dfar);
	
	float voxel = 0;

	if (!hit) {
	    pixel[0].x = 0;	pixel[0].y = 0;
	    pixel[0].z = 0;	pixel[0].w = 0;
	    return;
	}

	//-------------------------------------------
	//	Trace ray inside of box :
	const int MAX_STEPS = 300;
    float t = dnear;
    float dt = (dfar - dnear) / MAX_STEPS;
	for(int i=0; i<MAX_STEPS; i++) {		

        float3 pos = r.o + r.d*t;
        pos.z /= ss;
        pos = pos*0.5f+0.5f;    // map position to [0, 1] coordinates

		// compute gradient :
		float light = 1;
		/*if (1) {
			float dd = 1/256.0f;
			float3 grad;
			float3 light_dir = make_float3(1,1,1);
			grad.x =  (tex3D(mri_data, pos.x + dd, pos.y, pos.z) - tex3D(mri_data, pos.x - dd, pos.y, pos.z)) / (2*dd);
			grad.y =  (tex3D(mri_data, pos.x, pos.y + dd, pos.z) - tex3D(mri_data, pos.x, pos.y - dd, pos.z)) / (2*dd);
			grad.z =  (tex3D(mri_data, pos.x, pos.y, pos.z + dd) - tex3D(mri_data, pos.x, pos.y, pos.z - dd)) / (2*dd);
			grad = normalize(grad);
			light = 0.3*dot(grad, light_dir)+0.7;
			light = max(light, 0.0f);
		}*/
        
        //if ( pos.y>0.4 && pos.y<0.5 ) {
		if ( (pos.z<0.5 && pos.z>0.20) || pos.y>0.7 ) {
			float sample = tex3D(mri_data, pos.x, pos.y, pos.z);
			voxel = lerp(voxel, sample * light, sample*0.99);
		}

		

        t += dt;
        if (t > dfar) break;
    }
    
    //voxel /= 10.0f;

    pixel[0].x = voxel;
	pixel[0].y = voxel;
	pixel[0].z = voxel;
	pixel[0].w = voxel;

	    
    
}


//
//	CUDA_VisMRI
//
extern "C" 
void CUDA_VisMRI(void* screen, int scr_width, int scr_height, float *matrix, float t)
{
    cudaError_t error = cudaSuccess;
    
    CUDA_CHECK( cudaMemcpyToSymbol(inv_view_matrix, matrix, sizeof(float)*16) );

	//	Declare BLOCKS :
    dim3 Db = dim3( 8, 8 ); // block dimensions are fixed to be 256 threads
    dim3 Dg = dim3( (scr_width+Db.x-1)/Db.x, (scr_height+Db.y-1)/Db.y );
    
	CUDA_Tracer<<<Dg,Db>>>( (float4*)screen, scr_width, scr_height, t );
}
